<template>
  <div class="user-management">
    <div class="management-header">
      <h2>用户管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="showCreateDialog = true">
          <el-icon><Plus /></el-icon>
          添加用户
        </el-button>
        <el-button @click="showImportDialog = true">
          <el-icon><Upload /></el-icon>
          批量导入
        </el-button>
        <el-button @click="exportUsers">
          <el-icon><Download /></el-icon>
          导出用户
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="搜索">
          <el-input
            v-model="searchForm.search"
            placeholder="用户名、姓名、邮箱"
            clearable
            @keyup.enter="handleSearch"
            style="width: 250px"
          />
        </el-form-item>
        <el-form-item label="角色">
          <el-select
            v-model="searchForm.role"
            placeholder="选择角色"
            clearable
            @change="handleSearch"
            style="width: 150px"
          >
            <el-option label="管理员" value="admin" />
            <el-option label="教师" value="teacher" />
            <el-option label="学生" value="student" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.is_active"
            placeholder="选择状态"
            clearable
            @change="handleSearch"
            style="width: 120px"
          >
            <el-option label="启用" :value="true" />
            <el-option label="禁用" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item label="部门">
          <el-select
            v-model="searchForm.department"
            placeholder="选择部门"
            clearable
            @change="handleSearch"
            style="width: 150px"
          >
            <el-option
              v-for="dept in departments"
              :key="dept.id"
              :label="dept.name"
              :value="dept.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 用户列表 -->
    <el-card class="table-card">
      <template #header>
        <div class="table-header">
          <span>用户列表 ({{ pagination.total }})</span>
          <div class="batch-actions">
            <span v-if="selectedUsers.length > 0" class="selection-info">
              已选择 {{ selectedUsers.length }} 个用户
            </span>
            <el-button
              v-if="selectedUsers.length > 0"
              size="small"
              type="danger"
              @click="batchDelete"
            >
              批量删除
            </el-button>
            <el-button
              v-if="selectedUsers.length > 0"
              size="small"
              @click="batchToggleStatus"
            >
              批量切换状态
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="userList"
        @selection-change="handleSelectionChange"
        stripe
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="用户信息" min-width="200">
          <template #default="{ row }">
            <div class="user-info">
              <el-avatar
                :size="40"
                :src="row.avatar"
                :alt="row.username"
              >
                {{ row.first_name?.[0] || row.username?.[0]?.toUpperCase() }}
              </el-avatar>
              <div class="user-details">
                <div class="username">{{ row.username }}</div>
                <div class="full-name">{{ row.first_name }} {{ row.last_name }}</div>
                <div class="email">{{ row.email }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="角色" width="100">
          <template #default="{ row }">
            <el-tag :type="getRoleType(row.role)">
              {{ getRoleLabel(row.role) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="部门" prop="department" width="120" />
        <el-table-column label="班级" width="100">
          <template #default="{ row }">
            {{ row.class_name || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="手机号" prop="phone" width="120" />
        <el-table-column label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.is_active ? 'success' : 'danger'" size="small">
              {{ row.is_active ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="最后登录" width="150">
          <template #default="{ row }">
            {{ formatDateTime(row.last_login) }}
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="150">
          <template #default="{ row }">
            {{ formatDateTime(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" type="primary" link @click="editUser(row)">
              编辑
            </el-button>
            <el-button size="small" type="warning" link @click="resetPassword(row)">
              重置密码
            </el-button>
            <el-button
              size="small"
              :type="row.is_active ? 'danger' : 'success'"
              link
              @click="toggleUserStatus(row)"
            >
              {{ row.is_active ? '禁用' : '启用' }}
            </el-button>
            <el-popconfirm
              title="确定要删除这个用户吗？"
              @confirm="deleteUser(row.id)"
            >
              <template #reference>
                <el-button size="small" type="danger" link>删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 创建/编辑用户对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      :title="editingUser ? '编辑用户' : '添加用户'"
      width="600px"
      @close="resetUserForm"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userFormRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input
                v-model="userForm.username"
                :disabled="!!editingUser"
                placeholder="请输入用户名"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="userForm.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="!editingUser" :gutter="20">
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input
                v-model="userForm.password"
                type="password"
                placeholder="请输入密码"
                show-password
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="确认密码" prop="confirm_password">
              <el-input
                v-model="userForm.confirm_password"
                type="password"
                placeholder="请确认密码"
                show-password
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="first_name">
              <el-input v-model="userForm.first_name" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓氏" prop="last_name">
              <el-input v-model="userForm.last_name" placeholder="请输入姓氏" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="角色" prop="role">
              <el-select v-model="userForm.role" placeholder="请选择角色" style="width: 100%">
                <el-option label="管理员" value="admin" />
                <el-option label="教师" value="teacher" />
                <el-option label="学生" value="student" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门">
              <el-select v-model="userForm.department" placeholder="请选择部门" style="width: 100%">
                <el-option
                  v-for="dept in departments"
                  :key="dept.id"
                  :label="dept.name"
                  :value="dept.name"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="userForm.role === 'student'" :gutter="20">
          <el-col :span="12">
            <el-form-item label="班级">
              <el-select v-model="userForm.class_id" placeholder="请选择班级" style="width: 100%">
                <el-option
                  v-for="cls in classes"
                  :key="cls.id"
                  :label="cls.name"
                  :value="cls.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号">
              <el-input v-model="userForm.phone" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="状态">
              <el-switch
                v-model="userForm.is_active"
                active-text="启用"
                inactive-text="禁用"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" @click="saveUser" :loading="saving">
          {{ editingUser ? '更新' : '创建' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog v-model="showPasswordDialog" title="重置密码" width="400px">
      <el-form :model="passwordForm" :rules="passwordFormRules" label-width="100px">
        <el-form-item label="新密码" prop="new_password">
          <el-input
            v-model="passwordForm.new_password"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirm_password">
          <el-input
            v-model="passwordForm.confirm_password"
            type="password"
            placeholder="请确认新密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showPasswordDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmResetPassword" :loading="resetting">
          确认重置
        </el-button>
      </template>
    </el-dialog>

    <!-- 批量导入对话框 -->
    <el-dialog v-model="showImportDialog" title="批量导入用户" width="600px">
      <div class="import-content">
        <el-alert
          title="导入说明"
          description="请按照模板格式准备Excel文件，包含用户名、邮箱、姓名、角色等基本信息。"
          type="info"
          :closable="false"
        />
        <div class="upload-area">
          <el-upload
            class="upload-demo"
            drag
            :auto-upload="false"
            :on-change="handleFileChange"
            :limit="1"
            accept=".xlsx,.xls,.csv"
          >
            <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                只能上传 xlsx/xls/csv 文件，且不超过 10MB
              </div>
            </template>
          </el-upload>
        </div>
        <div class="template-download">
          <el-button type="text" @click="downloadTemplate">
            <el-icon><Download /></el-icon>
            下载导入模板
          </el-button>
        </div>
      </div>
      <template #footer>
        <el-button @click="showImportDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmImport" :loading="importing">
          确认导入
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Upload,
  Download,
  Search,
  UploadFilled
} from '@element-plus/icons-vue'
import { userApi } from '@/api'
import type { User } from '@/types'

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const resetting = ref(false)
const importing = ref(false)
const userList = ref<User[]>([])
const selectedUsers = ref<User[]>([])
const departments = ref<any[]>([])
const classes = ref<any[]>([])
const editingUser = ref<User | null>(null)

// 对话框状态
const showCreateDialog = ref(false)
const showPasswordDialog = ref(false)
const showImportDialog = ref(false)

// 搜索表单
const searchForm = reactive({
  search: '',
  role: '',
  is_active: null as boolean | null,
  department: '',
  page: 1,
  page_size: 20
})

// 分页
const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0
})

// 用户表单
const userFormRef = ref()
const userForm = reactive({
  username: '',
  email: '',
  password: '',
  confirm_password: '',
  first_name: '',
  last_name: '',
  role: '',
  department: '',
  class_id: null as number | null,
  phone: '',
  is_active: true
})

const userFormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度为3-20个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6个字符', trigger: 'blur' }
  ],
  confirm_password: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value !== userForm.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  first_name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

// 密码重置表单
const passwordForm = reactive({
  new_password: '',
  confirm_password: ''
})

const passwordFormRules = {
  new_password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6个字符', trigger: 'blur' }
  ],
  confirm_password: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value !== passwordForm.new_password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 导入文件
const importFile = ref<File | null>(null)

// 获取用户列表
const fetchUsers = async () => {
  loading.value = true
  try {
    const params = {
      ...searchForm,
      page: pagination.current,
      page_size: pagination.pageSize
    }

    // 过滤空值
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null) {
        delete params[key]
      }
    })

    const response = await userApi.getUsers(params)
    if (response.data) {
      userList.value = response.data.results
      pagination.total = response.data.count
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 获取部门和班级数据
const fetchBaseData = async () => {
  try {
    const [deptResponse, classResponse] = await Promise.all([
      userApi.getDepartments(),
      userApi.getClasses({ page_size: 1000 })
    ])

    if (deptResponse.data) {
      departments.value = deptResponse.data
    }

    if (classResponse.data?.results) {
      classes.value = classResponse.data.results
    }
  } catch (error) {
    console.error('获取基础数据失败:', error)
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchUsers()
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    search: '',
    role: '',
    is_active: null,
    department: ''
  })
  pagination.current = 1
  fetchUsers()
}

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.current = 1
  fetchUsers()
}

const handleCurrentChange = (page: number) => {
  pagination.current = page
  fetchUsers()
}

// 选择处理
const handleSelectionChange = (selection: User[]) => {
  selectedUsers.value = selection
}

// 重置用户表单
const resetUserForm = () => {
  Object.assign(userForm, {
    username: '',
    email: '',
    password: '',
    confirm_password: '',
    first_name: '',
    last_name: '',
    role: '',
    department: '',
    class_id: null,
    phone: '',
    is_active: true
  })
  editingUser.value = null
  userFormRef.value?.clearValidate()
}

// 编辑用户
const editUser = (user: User) => {
  editingUser.value = user
  Object.assign(userForm, {
    username: user.username,
    email: user.email,
    first_name: user.first_name,
    last_name: user.last_name,
    role: user.role,
    department: user.department,
    class_id: user.class_id,
    phone: user.phone,
    is_active: user.is_active
  })
  showCreateDialog.value = true
}

// 保存用户
const saveUser = async () => {
  try {
    await userFormRef.value.validate()

    saving.value = true
    const data = { ...userForm }
    delete data.confirm_password

    if (editingUser.value) {
      // 编辑时移除密码字段（如果为空）
      if (!data.password) {
        delete data.password
      }
      await userApi.updateUser(editingUser.value.id, data)
      ElMessage.success('用户更新成功')
    } else {
      await userApi.createUser(data)
      ElMessage.success('用户创建成功')
    }

    showCreateDialog.value = false
    fetchUsers()
  } catch (error) {
    console.error('保存用户失败:', error)
    ElMessage.error('保存用户失败')
  } finally {
    saving.value = false
  }
}

// 重置密码
const resetPassword = (user: User) => {
  editingUser.value = user
  Object.assign(passwordForm, {
    new_password: '',
    confirm_password: ''
  })
  showPasswordDialog.value = true
}

const confirmResetPassword = async () => {
  try {
    if (!passwordForm.new_password || passwordForm.new_password !== passwordForm.confirm_password) {
      ElMessage.error('请输入并确认新密码')
      return
    }

    resetting.value = true
    await userApi.resetUserPassword(editingUser.value!.id, {
      new_password: passwordForm.new_password
    })

    ElMessage.success('密码重置成功')
    showPasswordDialog.value = false
  } catch (error) {
    console.error('重置密码失败:', error)
    ElMessage.error('重置密码失败')
  } finally {
    resetting.value = false
  }
}

// 切换用户状态
const toggleUserStatus = async (user: User) => {
  try {
    await userApi.toggleUserStatus(user.id)
    ElMessage.success(`用户${user.is_active ? '禁用' : '启用'}成功`)
    fetchUsers()
  } catch (error) {
    console.error('切换用户状态失败:', error)
    ElMessage.error('切换用户状态失败')
  }
}

// 删除用户
const deleteUser = async (userId: number) => {
  try {
    await userApi.deleteUser(userId)
    ElMessage.success('用户删除成功')
    fetchUsers()
  } catch (error) {
    console.error('删除用户失败:', error)
    ElMessage.error('删除用户失败')
  }
}

// 批量删除
const batchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedUsers.value.length} 个用户吗？`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const userIds = selectedUsers.value.map(user => user.id)
    await userApi.batchDeleteUsers({ user_ids: userIds })

    ElMessage.success('批量删除成功')
    selectedUsers.value = []
    fetchUsers()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 批量切换状态
const batchToggleStatus = async () => {
  try {
    const userIds = selectedUsers.value.map(user => user.id)
    const newStatus = !selectedUsers.value[0].is_active

    await userApi.batchUpdateUsers({
      user_ids: userIds,
      updates: { is_active: newStatus }
    })

    ElMessage.success(`批量${newStatus ? '启用' : '禁用'}成功`)
    selectedUsers.value = []
    fetchUsers()
  } catch (error) {
    console.error('批量操作失败:', error)
    ElMessage.error('批量操作失败')
  }
}

// 导出用户
const exportUsers = async () => {
  try {
    await userApi.exportUsers({
      format: 'excel',
      ...searchForm
    })
    ElMessage.success('用户导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 导入处理
const handleFileChange = (file: any) => {
  importFile.value = file.raw
}

const confirmImport = async () => {
  if (!importFile.value) {
    ElMessage.warning('请选择要导入的文件')
    return
  }

  importing.value = true
  try {
    const response = await userApi.importUsers(importFile.value)
    if (response.data) {
      ElMessage.success(
        `导入完成：成功 ${response.data.imported} 个，跳过 ${response.data.skipped} 个`
      )
      if (response.data.errors.length > 0) {
        console.error('导入错误:', response.data.errors)
      }
    }

    showImportDialog.value = false
    fetchUsers()
  } catch (error) {
    console.error('导入失败:', error)
    ElMessage.error('导入失败')
  } finally {
    importing.value = false
  }
}

const downloadTemplate = () => {
  // TODO: 实现模板下载
  ElMessage.info('模板下载功能开发中')
}

// 工具函数
const getRoleType = (role: string) => {
  switch (role) {
    case 'admin': return 'danger'
    case 'teacher': return 'warning'
    case 'student': return 'success'
    default: return 'info'
  }
}

const getRoleLabel = (role: string) => {
  switch (role) {
    case 'admin': return '管理员'
    case 'teacher': return '教师'
    case 'student': return '学生'
    default: return role
  }
}

const formatDateTime = (dateTime: string | null) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 生命周期
onMounted(async () => {
  await Promise.all([
    fetchBaseData(),
    fetchUsers()
  ])
})
</script>

<style scoped lang="scss">
.user-management {
  padding: 20px;
}

.management-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  h2 {
    margin: 0;
    color: #303133;
  }

  .header-actions {
    display: flex;
    gap: 12px;
  }
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  .table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .batch-actions {
      display: flex;
      align-items: center;
      gap: 12px;

      .selection-info {
        color: #409eff;
        font-size: 14px;
      }
    }
  }

  .user-info {
    display: flex;
    align-items: center;
    gap: 12px;

    .user-details {
      .username {
        font-weight: 500;
        color: #303133;
      }
      .full-name {
        color: #606266;
        font-size: 14px;
      }
      .email {
        color: #909399;
        font-size: 12px;
      }
    }
  }

  .pagination-wrapper {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }
}

.import-content {
  .upload-area {
    margin: 20px 0;
  }

  .template-download {
    text-align: center;
    margin-top: 16px;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .user-management {
    padding: 12px;
  }

  .management-header {
    flex-direction: column;
    align-items: stretch;
    gap: 16px;

    .header-actions {
      justify-content: flex-start;
    }
  }

  .search-card .el-form {
    .el-form-item {
      margin-bottom: 16px;
      margin-right: 0;
    }
  }

  .table-card {
    .table-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 12px;

      .batch-actions {
        width: 100%;
        justify-content: space-between;
      }
    }
  }
}
</style>